package cn.yuanqiao.common.utils.sql;

import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
/***************************
                                *          春江花月夜(节选)   *
                                *              唐  张若虚    *
                                * 江畔何人初见月?江月何年初照人. *
                                * 人生代代无穷已,江月年年望相似. *
                                * 不知江月待何人,但见长江送流水. *
                                * 白云一片去悠悠,青枫浦上不胜愁. *
                                *****************************/

/**
 *@Author:       赵常飞
 *@Date:         2023/10/11 16:45
 *@Description:  用于处理不同数据库时,语法不一致,在此统一处理,避免后续适配时大范围修改
 *@Note:         新增方法时请与YQ_INSTR语法保持一致,便于维护
 */

@Component
public class YqDatabaseSQLUtil {
    private static String dataBaseId;

    @Resource
    private YqDatabaseIdProvider yqDatabaseIdProvider;

    public static String YQ_INSTR(String str, String subStr){
        if(DbIdEnum.DM.getCode().equalsIgnoreCase(dataBaseId)){
            return "FIELD("+subStr+","+str.replace("&apos;","'")+")";
        }else if(DbIdEnum.OSCAR.getCode().equalsIgnoreCase(dataBaseId)){
            String[] split = str.split(",");
            String s= "DECODE("+ subStr+",";
            for (int i = 0; i < split.length; i++) {
                if(i==split.length-1){
                    s+= "'"+split[i]+"',"+i;
                }else {
                    s+= "'"+split[i]+"',"+i+",";
                }
            }
            return s+")";
        }else if(DbIdEnum.HIGHGO.getCode().equalsIgnoreCase(dataBaseId)){
            return "position("+subStr+" in '"+str+"')";
        }else{
            return "instr('"+str.replace("'","&apos;")+"',concat("+subStr+"))";
        }
    }

    public static String YQ_ISNULL(String str1, String str2){
        if(DbIdEnum.DM.getCode().equalsIgnoreCase(dataBaseId)){
            return "IFNULL("+str1+","+str2+")";
        }else if(DbIdEnum.HIGHGO.getCode().equalsIgnoreCase(dataBaseId)){
            return " COALESCE("+str1+","+str2+")";
        }else{
            return "IFNULL("+str1+","+str2+")";
        }
    }

    /**
     * 字符串拼接
     * @param field
     * @return
     */
    public static String YQ_WM_CONCAT(String field){
        StringBuffer rtn=new StringBuffer();
        if(DbIdEnum.OPEN_GAUSS.getCode().equalsIgnoreCase(dataBaseId)){
            rtn.append("string_agg(").append(field).append("::TEXT,',')");
            return rtn.toString();
        }else{
            rtn.append("wm_concat(").append(field).append(")");
            return rtn.toString();
        }
    }

    @PostConstruct
    public void getDatabaseId() {
        dataBaseId =  yqDatabaseIdProvider.getDatabaseId();
    }

}
